package com.darkness.rpc.framework.provider;

import com.darkness.rpc.framework.protocol.Protocol;
import com.darkness.rpc.registercenter.Register;
import com.darkness.rpc.registercenter.local.LocalRegister;
import org.apache.dubbo.common.extension.ExtensionLoader;

import java.net.InetAddress;
import java.util.List;
import java.util.Map;

public class RpcProvider {

    // 由于要根据协议注册, 因此key就是协议名, value是该协议下要注册的服务列表
    private final Map<String, List<Service>> servicesMap;

    public RpcProvider(Map<String, List<Service>> servicesMap) {
        this.servicesMap = servicesMap;
    }

    public void startProvider(String registry, Integer port) {
        try {
            // 注册服务(注册中心), 根据注册中心类型选择不同实现类去注册, 本demo使用file(本地文件)或者boot(另开一个springboot程序注册)
            Register register = ExtensionLoader.getExtensionLoader(Register.class).getExtension(registry);
            for (String protocol : servicesMap.keySet()) {
                int protocolPort = port;
                List<Service> services = servicesMap.get(protocol);
                for (Service service : services) {
                    register.register(service.getGroup(), service.getVersion(), service.getItfClass().getName(), InetAddress.getLocalHost().getHostAddress(), port);
                    // 服务端需要在本地缓存注册一下实现类, 实现类只需要服务提供者自己知道, 因此使用本地缓存注册
                    LocalRegister.registerLocal(service.getGroup(), service.getItfClass().getName(), service.getVersion(), service.getImplClass());
                }
                // 启动服务器
                Protocol protocolServer = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(protocol);
                // 开启线程启动服务器, 协议为http就启动tomcat, 协议为dark就启动netty
                new Thread(() -> protocolServer.startServer(protocolPort)).start();
                port++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
